<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Validator;
use Illuminate\Http\Request;
use App\Libraries\Weixin;
use DB;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Foundation\Application;
use App\Models\User;

class UserController extends Controller {

    public function index(Application $wechat) {
        if (empty(session('wechat_userinfo'))) {
            session(['target_url' => 'my']);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $user = User::where('openid', session('wechat_userinfo.openid'))->first();
        if (!$user) {
            return redirect('/register');
        }
        return view('wechat.user.personal', ['user' => $user,'avatar'=>session('wechat_userinfo.headimgurl')]);
    }

    public function order(Application $wechat) {
        if (empty(session('wechat_userinfo'))) {
            session(['target_url' => 'my/order']);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $user = User::where('openid', session('wechat_userinfo.openid'))->first();
        if (!$user) {
            return redirect('/register');
        }
        $orders = $user->orders;
        return view('wechat.my.order', ['orders' => $orders]);
    }

    public function bill(Application $wechat) {
        if (empty(session('wechat_userinfo'))) {
            session(['target_url' => 'my/order']);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $user = User::where('openid', session('wechat_userinfo.openid'))->first();
        if (!$user) {
            return redirect('/register');
        }
        $orders = $user->orders()->where('state',1)->get();
        return view('wechat.my.bill', ['orders' => $orders]);
    }

}
